﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Permissions;
using System.Threading;

namespace Deep_Talk_Converter.ProcessPriorityUtils
{
    /// <summary>
    /// Put a thread into background mode processing. Stollen from
    /// http://code.logos.com/blog/2008/10/using_background_processing_mode_from_c.html
    /// </summary>
    public static class ProcessUtility
    {
        /// <summary>
        /// Puts the current thread into background processing mode.
        /// </summary>
        /// <returns>A Scope that must be disposed to leave background processing mode.</returns>
        [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlThread)]
        public static Scope EnterBackgroundProcessingMode()
        {
            IntPtr hProcess = NativeMethods.GetCurrentProcess();
            if (IsWindowsVista() && NativeMethods.SetPriorityClass(hProcess,
                Win32.PROCESS_MODE_BACKGROUND_BEGIN))
            {
                // OS supports background processing; return Scope that exits this mode
                return Scope.Create(() =>
                {
                    NativeMethods.SetPriorityClass(hProcess, Win32.PROCESS_MODE_BACKGROUND_END);
                });
            }

            // OS doesn't support background processing mode (or setting it failed)
            return Scope.Empty;
        }

        // Returns true if the current OS is Windows Vista (or Server 2008) or higher.
        private static bool IsWindowsVista()
        {
            OperatingSystem os = Environment.OSVersion;
            return os.Platform == PlatformID.Win32NT && os.Version >= new Version(6, 0);
        }
    }
}
